package user

import (
	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"ticket/captcha/service"
)

// 登录函数
func LoginFunc(r *ghttp.Request) (string, interface{}) {
	jsonData, err := r.GetJson()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{"error": "Invalid JSON data"})
		return "", nil
	}

	// 从Map中获取数据
	username := jsonData.Get("username").String()
	password := jsonData.Get("password").String()
	verifyCode := jsonData.Get("verifyCode").String()
	verifyKey := jsonData.Get("verifyKey").String()

	// 使用解析出的数据进行操作
	verifyCodeVaild(r, verifyKey, verifyCode)

	// 验证账户是否禁用
	IsBind(r, username)

	// 验证账号密码
	findUser(r, username, password)

	// 验证成功，返回用户名【GToken 会自动根据返回的内容从而给出 Token】
	return username, nil
}

// 校验验证码是否有效
func verifyCodeVaild(r *ghttp.Request, verifyKey string, verifyCode string) {
	if !service.Captcha().VerifyString(verifyKey, verifyCode) {
		r.Response.WriteJsonExit(g.Map{
			"code": 200,
			"msg":  "验证码错误",
		})
	}
}

// 验证用户名和密码
func findUser(r *ghttp.Request, username string, password string) {
	encryptedPassword, _ := gmd5.Encrypt(password)
	count, err := g.Model("user_agents").Where("username=? AND password=? AND status<>-1", username, encryptedPassword).Count()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": 500,
			"msg":  "内部错误，数据库查询失败",
		})
	}

	if count == 0 {
		r.Response.WriteJsonExit(g.Map{
			"code": 401,
			"msg":  "认证失败，用户名或密码错误",
		})
	}
}

// 账号是否禁用
func IsBind(r *ghttp.Request, username string) error {
	one, err := g.Model("user_agents").Where("username=? AND status = -1", username).One()
	if err != nil {
		r.Response.WriteJsonExit(g.Map{
			"code": 500,
			"msg":  "内部错误，数据库查询失败",
		})
	}

	// 用户名或密码不匹配
	if !one.IsEmpty() {
		r.Response.WriteJsonExit(g.Map{
			"code": 200,
			"msg":  "账号已被禁用",
		})
	}
	return err
}
